package com.dream.technology.components.expresion.imp;

import com.dream.technology.components.context.FlowContext;
import com.dream.technology.components.engine.JsEngineEVel;
import com.dream.technology.components.expresion.ExpressionService;
import com.dream.technology.components.expresion.RiskExpressionAnaMatcher;
import com.dream.technology.db.entity.RcCustomerTag;
import com.dream.technology.db.entity.RcCustomerTagItem;
import com.dream.technology.db.entity.vo.RiskItemVo;
import com.dream.technology.db.entity.vo.VoCustomerTag;
//import com.dream.technology.zycashLog.Console;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述：标签表达式解析
 * <p>
 * A ＆＆ B ＆＆C ＆＆{（D＆＆E）｜（F＆＆H）｜(I＆＆J)}＆＆K
 * 替换为  true ＆＆ true ＆＆Ctrue＆＆{（true|false）}
 * 替换掉 {} 为（）
 * js引擎执行
 *
 * @author chen_q_i@163.com
 * 2019/1/3 : 18:48.
 * @version : 1.0
 */
@Slf4j
@Component("tagExpressionAnalysis")
public class TagExpressionAnalysis {

    @Autowired
    private RiskExpressionAnaMatcher riskExpressionAnaMatcher;

    public boolean analysisTag(VoCustomerTag tag, FlowContext context) {
        Boolean eval = false;
        // 遍历标签的每一个配置
        List<RcCustomerTagItem> customerTagItems = tag.getCustomerTagItems();
        RcCustomerTag customerTag = tag.getCustomerTag();
        String tagRule = customerTag.getTagRule();
        // 替换{}
        tagRule = tagRule.replaceAll("\\{", "(");
        tagRule = tagRule.replaceAll("}", ")");

        Map<String, RcCustomerTagItem> collect = customerTagItems.stream().collect(Collectors.toMap(RcCustomerTagItem::getTagItemAlias, cusItem -> cusItem));

        for (RcCustomerTagItem item : customerTagItems) {
            // 生成表达式 根据不同数据格式选择不同的执行
            //分别有 数字1 ，boolean 2,radio 3,checkbox 4, datetime 5, string 6
            Integer fieldDataType = item.getFieldDataType();
            ExpressionService expressionServices = riskExpressionAnaMatcher.getExpressionServices(fieldDataType);
            RiskItemVo voItem = item.getVoItem();

            boolean b = expressionServices.expressionAnalysis(context, voItem);
            log.info("执行节点 ：{} 表达式 ：{} 结果 ：{}",voItem.getFieldName(),voItem.getOperationalSymbolCode(), b);
            // 别名替换
             tagRule = tagRule.replace(item.getTagItemAlias(), String.valueOf(b));
        }
        Boolean aBoolean = JsEngineEVel.getBoolean(tagRule);
        return  aBoolean;
    }

}
